import pysvn
import os
import stat
import shutil
import logging

LOCAL_SVN_PATH = 'task/script'

def OnDeleteError(f, p, e):
    os.chmod(p, stat.S_IWRITE)
    if os.path.isdir(p):
        os.rmdir(p)
    else:
        os.remove(p)
    

class SvnClien():
    def __init__(self):
        self.user = None
        self.password = None
        self.svn = pysvn.Client()
        self.svnpath = None
        self.svn.callback_get_login = self.GetLogin
    
    def GetLogin(self, realm, user, may_save):
        return True, self.user, self.password, False
    
    def SetSvnInfo(self, path, user, password):
        self.user = user
        self.password = password
        self.svnpath = path
        
        url = None
        try:
            if os.path.exists(LOCAL_SVN_PATH):
                url = self.svn.info(LOCAL_SVN_PATH).url
        except Exception:
            logging.exception('svn get info error')
             
        try:
            if url != path:
                shutil.rmtree(LOCAL_SVN_PATH, onerror = OnDeleteError)
                self.svn.checkout(self.svnpath, LOCAL_SVN_PATH)
            else:
                self.svn.update(LOCAL_SVN_PATH)
        except Exception:
            logging.exception('svn operator fail')
            
    def Update(self):
        try:
            self.svn.update(LOCAL_SVN_PATH)
        except Exception:
            logging.exception('svn operator fail')
            
